#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
using namespace std;
const int N = 10;
char g[N][N], bp[N][N];
int dx[5] = { 0, -1, 0, 1, 0 }, dy[5] = { 0, 0, 1, 0, -1 };
void turn(int x, int y) {
	for (int i = 0; i < 5; i++) {
		int a = x + dx[i], b = y + dy[i];
		if (a >= 0 && a < 5 && b >= 0 && b < 5) {
			bp[a][b] ^= 1;
		}
	}
}
int main()
{
	int t;
	scanf("%d", &t);
	while (t--) {
		memset(g, 0, sizeof(g));
		memset(bp, 0, sizeof(bp));
		for (int i = 0; i < 5; i++) {
			scanf("%s", g[i]);
		}
		int ans = 10;
		for (int i = 0; i < 32; i++) {
			int cnt = 0;
			memcpy(bp, g, sizeof(g));
			for (int j = 0; j < 5; j++) {
				if (i >> j & 1) {
					turn(0, j);
					cnt++;
				}
			}
			for (int j = 1; j <= 4; j++) {
				for (int k = 0; k < 5; k++) {
					if (bp[j- 1][k] == '0') {
						turn(j, k);
						cnt++;
					}
				}
			}
			bool flag = 1;
			for (int j = 0; j < 5; j++) {
				if (bp[4][j] == '0') {
					flag = 0;
					break;
				}
			}
			if (flag) {
				ans = min(ans, cnt);
			}
		}
		if (ans > 6) {
			cout << -1 << endl;
		}
		else {
			cout << ans << endl;
		}
	}
	return 0;
}